/************* 文件上传 *************/
export default class UploadFile {
    private options: any = {
        baseUrl: '',
        url: '',
        timeout: 1000 * 5,
        name: 'file',
        header: {},
    }

    private static mInstance: UploadFile;

    constructor(options?: any) {
        this.options = options;
    }

    // 单例模式创建
    public static getInstance(options: any = {}): UploadFile {
        if (!UploadFile.mInstance) {
            UploadFile.mInstance = new UploadFile(options);
        }
        return UploadFile.mInstance;
    }

    // 下载拦截器
    private static upBefore = (config: any) => (config);

    // 拦截器
    public interceptors = {
        // Function | object
        request: (func: any) => {
            if (func) {
                UploadFile.upBefore = func
            }
            else {
                UploadFile.upBefore = (config: any) => config
            }
        },
    }

    // 是否是完整的url路径
    private static isCompleteURL = (url: string) => /(http|https):\/\/([\w.]+\/?)\S*/.test(url);

    /**
     * 下载
     * @param options 下载参数
     * @param callback 下载任务回调
     * @returns 
     */
     public upload(options: any, TaskFunc: Function): Promise<any> {
        options.url = UploadFile.isCompleteURL(options.url) ? options.url : this.options.baseUrl + options.url;
        // 合并请求参数重复则覆盖
        options = Object.assign(this.options, UploadFile.upBefore(options));
        return new Promise((resolve,reject)=> {
            options.success = (res: any) => {
                resolve(res)
            }
            options.fail = (error: any) => {
                reject(error)
            }
            const uploadTask: UniNamespace.UploadTask = uni.uploadFile(options)
            TaskFunc(uploadTask)
        })
    }
}